<?php

namespace App\Console\Commands\CallingCards;

use App\Models\Common\ConfigModel;
use App\Remote\XiaoKe\CustomerRemote;
use Illuminate\Console\Command;

class UpdateXiaokeAreas extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'calling_cards:update_xiaoke_areas';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '[加盟名片]更新销氪二级地址';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $res = CustomerRemote::areas();
        if (!is_array($res)) {
            return 0;
        }
        $list = [];
        foreach ($res as $v) {
            foreach ($v['areaInfoList'] as $vv) {
                if (!isset($list[$v['areaCode']])) {
                    $list[$v['areaCode']] = [
                        'code'   => $v['areaCode'],
                        'name'   => $v['areaName'],
                        'childs' => [],
                    ];
                }
                $list[$v['areaCode']]['childs'][$vv['areaCode']] = [
                    'code' => $vv['areaCode'],
                    'name' => $vv['areaName'],
                ];
            }
        }
        foreach ($list as $k => $v) {
            $list[$k]['childs'] = array_values($v['childs']);
        }
        $list = array_values($list);
        $m    = ConfigModel::where('module', 'callingCards')
            ->where('name', 'xiaokeAreas')
            ->first();
        if (null === $m) {
            $m = new ConfigModel();
            $m->setAttribute('module', 'callingCards');
            $m->setAttribute('name', 'xiaokeAreas');
        }
        $m->setAttribute('description', '销氪二级地址库，定时自动更新');
        $m->setAttribute('type', 'json');
        $m->setAttribute('public', '1');
        $m->setAttribute('value', json_encode($list, JSON_UNESCAPED_UNICODE));
        $m->save();
        return 0;
    }
}
